import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;

public class SnakePanel extends JPanel {
    //public static int[] foodPoint = new int[]{-1, -1};

    public SnakePanel() {
        setBounds(0, 0, MainFrame.WIDTH, MainFrame.WIDTH);
        setBackground(new Color(0,0,0));
    }

    /**
     * 绘制面板的内容: 创建 JPanel 后会调用一次该方法绘制内容,
     * 之后如果数据改变需要重新绘制, 可调用 updateUI() 方法触发
     * 系统再次调用该方法绘制更新 JPanel 的内容。
     */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawSnake(g);

        /*if (foodPoint[0] == -1 || MainFrame.xyPoint.contains(foodPoint[0] + "," + foodPoint[0])) {
            System.out.println("drawfood");
            drawFood(g);
        }*/
    }

    private void drawSnake(Graphics g) {
        //获取当前路径坐标数组，并转换成int数组
        int[] xPoints = Arrays.stream(MainFrame.xPoint.toArray(new Integer[0])).mapToInt(Integer::valueOf).toArray();
        int[] yPoints = Arrays.stream(MainFrame.yPoint.toArray(new Integer[0])).mapToInt(Integer::valueOf).toArray();
        // 创建 Graphics 的副本, 需要改变 Graphics 的参数,
        // 这里必须使用副本, 避免影响到 Graphics 原有的设置
        Graphics2D g2d = (Graphics2D) g.create();

        // 抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 设置画笔颜色
        g2d.setColor(Color.WHITE);
        // 多点绘制折线
        int nPoints = xPoints.length;
        //System.out.println("点的个数： "+nPoints);
        BasicStroke bs3 = new BasicStroke((float) (MainFrame.GRID_WIDTH * 0.8));// 笔画的轮廓（画笔宽度为格子的80%）
        g2d.setStroke(bs3);

        g2d.drawPolyline(xPoints, yPoints, nPoints);

        // 自己创建的副本用完要销毁掉
        g2d.dispose();
    }

}
